(function($, doc) {
	$.plusReady(function() {
		var user = app.getState();
		var uid = user.user_id;
		var self = plus.webview.currentWebview();
		var roomId = self.roomId;
		var roomType = self.roomType;
		var pageType = self.pageType;
		var myWallet;
		var coinlist = {};
		ethscan.getmyCoin(function(data) {
			coinlist = data;
		});
		console.log(roomType);
		if(roomType > 1) {
			doc.getElementById('countarea').style.display = '';
			doc.getElementById('typearea').style.display = '';
		}
		var coindata;
		var selecthtml = '';
		for(var p in coinlist) {
			selecthtml += '<option value="' + p + '">' + coinlist[p]['name'] + '</option>';
		}
		doc.getElementById('selected_tokens').innerHTML = selecthtml;
		var nativeWebview, imm, InputMethodManager;
		var initNativeObjects = function() {
			if(mui.os.android) {
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
				imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
			} else {
				nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
			}
		};
		var showSoftInput = function() {
			if(mui.os.android) {
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
			} else {
				nativeWebview.plusCallMethod({
					"setKeyboardDisplayRequiresUserAction": false
				});
			}
			setTimeout(function() {
				//此处可写具体逻辑设置获取焦点的input
				var inputElem = doc.querySelector('#money');
				inputElem.focus();
			}, 200);
		};
		initNativeObjects();
		showSoftInput();
		doc.getElementById("money").focus();
		var helpbtn = doc.getElementById('red_packet');
		helpbtn && helpbtn.addEventListener("tap", function() {
			mui.openWindow({
				url: '../../pages/system/redpacket_help.html',
				id: '../../pages/system/redpacket_help.html'
			});
		});
		doc.getElementById('money').addEventListener('input', function() {
			this.value = this.value.replace(/[^\d.]/g, '');

			if(isNaN(this.value) || this.value < 0) {
				$.toast('请输入数字');
				mui('.mui-btn-danger.mui-btn-block')[0].style.opacity = 0.3;
				this.value = 0;
				return;
			}
			doc.getElementById('all_money').innerHTML = this.value;
			mui('.mui-btn-danger.mui-btn-block')[0].style.opacity = 1;
		});
/*
		function paymoney(amount, etype) {
			plus.nativeUI.closeWaiting();
			var btnArray = ['确定', '取消'];
			mui.prompt('请输入钱包密码', '', '', btnArray, function(e) {
				if(e.index == 0) {
					console.log(e.value);

					if(e.value && e.value.length > 0) {
						if(md5(e.value) != myWallet.passwd) {
							$.toast("密码错误！");
							plus.nativeUI.closeWaiting();
							return;
						} else {
							plus.nativeUI.showWaiting("支付中...");
							if(etype == 'eth' || etype == 'ethcontact') {
								ptype = 'eth';
							} else {
								ptype = 'btc';
							}
							ethscan.getWallet(uid, ptype, function(res) {
								if(res.status) {
									if(roomType < 2) {
										if(etype == 'eth') {
											payeth(amount, res.address);
										} else {
											paycontract(amount, res.address);
										}
									} else {
										//群红包
										plus.nativeUI.closeWaiting();
										dopost(uid + '-' + app.now(), res.address);
									}
								} else {
									$.toast('对方没有创建钱包！');
									return;
								}
							});

						}
						
						var postdata = {
							uid: uid,
							etype: 'eth',
							tid: roomId,
							passwd: md5(e.value)
						};
						plus.nativeUI.showWaiting("支付中...");
						//console.log(JSON.stringify(postdata));
						$.post(apiurl + 'token/getUserWallet', postdata, function(res) {
							console.log(JSON.stringify(res));
							if(res.status > -1) {
								//tranfer(res.addr, amount);

							} else {
								$.toast(res.msg);
								plus.nativeUI.closeWaiting();
								return;
							}
						});
					} else {
						$.toast("密码不能为空！");
					}
				} else {

					//info.innerText = '你点了取消按钮';
				}
			}, 'div');
		}*/
		/*
		function paycontract(amount, toaddr) {
			var providers = ethers.providers;
			var provider = providers.getDefaultProvider('homestead');
			var wallet = new ethers.Wallet(myWallet.privkey, provider);
			var contract = new ethers.Contract(coindata['address'], coindata['abi'], wallet);

			var options = {
				//gasPrice: 1100000000, // 1.1Gwei
				gasLimit: 250000
			};
			plus.nativeUI.closeWaiting();
			var callPromise = contract.transfer(toaddr, amount, options);
			callPromise.then(function(obj) {
				console.log(JSON.stringify(obj));
				$.toast('支付成功，打包需要3-5分钟！');
				dopost(obj.hash, toaddr);
			})

			callPromise.catch(function(error) {
				console.log(JSON.stringify(error));
				$.toast('支付失败！');
			});
		}

		function payeth(amount, toaddr) {
			var privateKey = myWallet.privkey;
			var wallet = new ethers.Wallet(privateKey);
			wallet.provider = ethers.providers.getDefaultProvider();
			var sendPromise = wallet.send(toaddr, amount);

			sendPromise.then(function(transactionHash) {
				console.log(transactionHash);
			});

			var options = {
				gasLimit: 21000
			};

			var promiseSend = wallet.send(toaddr, amount, options);
			plus.nativeUI.closeWaiting();
			promiseSend.then(function(transaction) {
				console.log(transaction);
				$.toast('支付成功，打包需要3-5分钟！');
				dopost(transaction.hash, toaddr);
			});
			promiseSend.catch(function(error) {
				console.log(JSON.stringify(error));
				$.toast('支付失败！');
			});
		}*/
		ethscan.checklasthash(function(res) {
			console.log(JSON.stringify(res));
			if(res.status > 0){
				$.toast(res.msg);
			}
		});

		//checkcanTrade(user.eth_address);

		function dopost(hash, toaddr) {
			if(pageType == 'hongbao') {
				var count = doc.getElementById('count').value || 1;
				var typeselct = doc.getElementById('packettype');
				var index = typeselct.selectedIndex;
				var ptype = typeselct.options[index].value;
			} else {
				var count = 1;
				var ptype = 1;
			}

			var money = doc.getElementById('money').value;
			var remark = doc.getElementById('remark').value;
			if(roomType < 2) {
				ptype = 1;
			}
			var postdata = {
				hash: hash,
				uid: uid,
				tid: roomId,
				myaddr: myWallet.address,
				toaddr: toaddr,
				sysaddr: '',
				remark: remark,
				token: coindata['address'],
				amount: money,
				nums: count,
				etype: ptype,
				roomtype: roomType,
				coinname : coindata['name']
			};
			//console.log(JSON.stringify(postdata));
			var s = apiurl + 'trade/addtrade?';
			for(var p in postdata) {
				s += p + '=' + postdata[p] + '&';
			}
			console.log(s);
			//return;
			$.post(apiurl + 'trade/addtrade', postdata, function(res) {
				console.log(JSON.stringify(res));
				if(res.status && res.status > 0) {
					var chatbox = plus.webview.getWebviewById("chatbox");
					mui.fire(chatbox, 'PAY_HONGBAO_SUCC', {
						fromtype: ptype,
						remark: remark,
						money: money,
						hash: hash,
						pageType: pageType
					});
					//var service_comfirm = plus.webview.getWebviewById("red_packet");
					//plus.webview.close(service_comfirm, "none");
					plus.webview.currentWebview().close();
					plus.webview.show('chatbox');
				} else {
					$.alert(res.msg);
				}
			});
		}

		doc.getElementById('subredpacket').addEventListener('tap', function() {
			var money = doc.getElementById('money').value;
			var coinselect = doc.getElementById("selected_tokens");
			var index = coinselect.selectedIndex;
			var coinkey = coinselect.options[index].value;
			coindata = coinlist[coinkey];
			var ctype = coindata['ctype'];
			if(ctype == 'ethcontact') {
				//console.log(addrs);
				coindata['abi'] = ethscan.getabi(coinkey);
				//console.log(coindata['abi']);
			}
			
			if(ctype == 'ethcontact' || ctype == 'eth') {
				myWallet = ethscan.getWallet('eth');
			} else {
				myWallet = ethscan.getWallet('btc');
			}
			/*var addr = myWallet.address;
			if(!addr) {
				$.alert("您还没有设定默认钱包");
				$.openWindow({
					url: "mgrwallet.html",
					id: "mgywallet"
				});
				return;
			}*/
			if(isNaN(money) || money < 0) {
				$.toast('请输入正确的数字');
				return;
			}
			if(money < 0.0001) {
				$.alert("支付金额不能低于0.0001");
				return;
			}
			//群
			if(roomType > 1) {
				var count = doc.getElementById('count').value;
				if(isNaN(count) || count < 0) {
					$.toast('请输入正确的数字');
					return;
				}

			}
			ethscan.checkPwd(ctype, function() {
				if(ctype == 'btc') {
					$.toast('开发中！');
					return;
				} else {
					if(roomType < 2) {
						ethscan.payToUserEth(roomId, ctype, coindata, money, function(obj, toaddr) {
							dopost(obj.hash, toaddr);
						}, function(err) {
							console.log(err);
							$.toast('支付失败！');
						});
					} else {
						ethscan.checkPayMoney(money,coindata, function(){
							dopost(uid + '-' + app.now(), '');
						});
						
					}

					return;
				}
			}, function() {
				$.alert("您还没有设定默认钱包");
				$.openWindow({
					url: "mgrwallet.html",
					id: "mgywallet"
				});
				return;
			});

			//plus.nativeUI.showWaiting("钱包校验中...");
			//var amount = ethers.utils.parseEther(money);
			//var providers = ethers.providers;
			//var provider = providers.getDefaultProvider('homestead');
			/*
			if(ctype == 'eth' || ctype == 'ethcontact') {
				ethscan.checkEthAmount(money, ctype, coindata, function(){
					paymoney(money, 'ethcontract');
				});
				
				provider.getBalance(myWallet.address).then(function(balance) {
					var etherString = ethers.utils.formatEther(balance);
					console.log(JSON.stringify(etherString));

					if(ctype == 'ethcontact') {
						if(etherString < 0.001) {
							$.alert("您至少要持有0.001ETH来保证矿工费支付");
							plus.nativeUI.closeWaiting();
							return;
						}
						var contracts = new ethers.Contract(coindata['address'], coindata['abi'], provider);
						contracts.balanceOf(myWallet.address).then(function(res) {
							//item['money'] = res["_bn"];
							var contractsetherString = ethers.utils.formatEther(res);
							if(money > contractsetherString) {
								$.alert(coindata['name'] + "账户余额不足");
								plus.nativeUI.closeWaiting();
								return;
							}
							//paycontract(amount);
							paymoney(amount, 'ethcontract');
						});
					} else {
						if(money > etherString) {
							$.alert("ETH账户余额不足");
							plus.nativeUI.closeWaiting();
							return;
						}
						//payeth(amount);
						paymoney(amount, 'eth');
					}
				});
			} else {
				$.toast('开发中！');
				return;
			}*/

			//if(ctype == 'ethcontact') {

			//}
			return;
			//console.log(coinkey);
		});
	});
}(mui, document));